//
//  NoteViewController.m
//  Exam11-3
//
//  Created by 孙晓晔 on 2017/4/16.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "NoteViewController.h"
#import <sqlite3.h>
#import "NoteAddController.h"
#import "NoteEditController.h"
#import "NoteViewCell.h"

@interface NoteViewController ()<NoteAddControllerDelegate, NoteEditControllerDelegate>
@property(nonatomic,strong) NSMutableArray *noteArr; // 数据
@end

@implementation NoteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self setUp];
}

// 懒加载
-(NSMutableArray *)noteArr {
    if (_noteArr == nil) {
        
        NSMutableArray *arr = [NSMutableArray array];
        
        sqlite3 *db = [self openDb];
        
        char *sql = "SELECT * FROM note ORDER BY id DESC";
        sqlite3_stmt *stmt = NULL;
        
        int ret = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
        if (ret == SQLITE_OK) {
            NSLog(@"执行SQL查询语句成功。", nil);
            
            while (sqlite3_step(stmt) == SQLITE_ROW) {
                
                int uid = sqlite3_column_int(stmt, 0);
                char *content = (char*)sqlite3_column_text(stmt, 1);
                char *datetime = (char*)sqlite3_column_text(stmt, 2);
                
                Note *note = [[Note alloc]init];
                note.uid = uid;
                note.content = [NSString stringWithUTF8String:content];
                
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                note.createTime = [dateFormatter dateFromString:[NSString stringWithUTF8String:datetime]];
                
                [arr addObject:note];
            }
        } else {
            NSLog(@"执行SQL查询语句失败。错误码 = %d" , ret);
        }
        
        sqlite3_finalize(stmt);
        
        [self closeDb:db];
        
        _noteArr = arr;
    }
    
    return _noteArr;
}

// 新增信息
- (void)addNote:(NoteAddController *)addController note:(Note *)note {
    NSLog(@"add note 68.", nil);
    
    sqlite3 *db = [self openDb];
    
    NSString *str = [NSString stringWithFormat:@"insert into note(content, createTime) values('%@', datetime(CURRENT_TIMESTAMP, 'localtime'))", note.content];
    
    const char *sql = [str UTF8String];
    char *err;
    
    int ret = sqlite3_exec(db, sql, NULL, NULL, &err);
    if (ret == SQLITE_OK) {
        NSLog(@"执行SQL语句成功。", nil);
    } else {
        NSLog(@"执行SQL语句失败。错误码 = %d" , ret);
    }
    
    [self closeDb:db];
    
    self.noteArr = nil;
    
    // 刷新表视图
    [self.tableView reloadData];
}

// 编辑信息
- (void)editNote:(NoteEditController *)editController note:(Note *)note {
    NSLog(@"edit note 72.", nil);
    
    sqlite3 *db = [self openDb];
    
    NSString *str = [NSString stringWithFormat:@"update note set content = '%@' where id = %ld", note.content, note.uid];
    
    NSLog(str, nil);
    
    const char *sql = [str UTF8String];
    char *err;
    
    int ret = sqlite3_exec(db, sql, NULL, NULL, &err);
    if (ret == SQLITE_OK) {
        NSLog(@"执行SQL语句成功。", nil);
    } else {
        NSLog(@"执行SQL语句失败。错误码 = %d" , ret);
    }
    
    [self closeDb:db];
    
    [self.tableView reloadData];
}

// 创建表结构
-(void)setUp {
    const char *sql = "create table if not exists note(id integer primary key autoincrement, content varchar, createtime DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')))";
    
    sqlite3 *db = [self openDb];
    
    char *err;
    
    int ret = sqlite3_exec(db, sql, NULL, NULL, &err);
    if (ret == SQLITE_OK) {
        NSLog(@"执行SQL语句成功。", nil);
    } else {
        NSLog(@"执行SQL语句失败。错误码 = %d" , ret);
    }
    
    [self closeDb:db];
}

// 打开数据库
-(sqlite3*)openDb {
    const char *filename = [[self path] UTF8String];
    
    sqlite3 *db = NULL;
    
    int ret = sqlite3_open(filename, &db);
    
    if (ret == SQLITE_OK) {
        NSLog(@"打开数据库成功。", nil);
    } else {
        NSLog(@"打开数据库失败。错误码 = %d" , ret);
    }
    
    return db;
}

// 关闭数据库
-(void)closeDb:(sqlite3*)db {
    int ret = sqlite3_close(db);
    if (ret == SQLITE_OK) {
        NSLog(@"关闭数据库成功。", nil);
    } else {
        NSLog(@"关闭数据库失败。错误码 = %d" , ret);
    }
}

// 设置数据库文件
-(NSString*)path {
    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *strDoc = [arr firstObject];
    
    NSLog(strDoc, nil);
    
    return [NSString stringWithFormat:@"%@/sqlite.db", strDoc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

// 设置行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.noteArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"notecell";
    
    NoteViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"NoteViewCell" owner:nil options:nil] firstObject];
        
        cell.model = self.noteArr[indexPath.row];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        Note *note = self.noteArr[indexPath.row];
        
        [self deleteNote:note];
        
        [self.noteArr removeObjectAtIndex:indexPath.row];
        
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

// 删除数据
-(void)deleteNote:(Note*)note {
    sqlite3 *db = [self openDb];
    
    NSString *str = [NSString stringWithFormat:@"delete from note where id = %ld", note.uid];
    
    NSLog(str, nil);
    
    const char *sql = [str UTF8String];
    char *err;
    
    int ret = sqlite3_exec(db, sql, NULL, NULL, &err);
    if (ret == SQLITE_OK) {
        NSLog(@"执行SQL语句成功。", nil);
    } else {
        NSLog(@"执行SQL语句失败。错误码 = %d" , ret);
    }
    
    [self closeDb:db];
}

/**
 *  修改Delete按钮文字为“删除”
 */
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (IBAction)edit:(UIBarButtonItem *)sender {
    
    if ([sender.title isEqual: @"编辑"]) {
        sender.title = @"确定";
        [self.tableView setEditing:YES animated:YES];
    } else {
        sender.title = @"编辑";
        [self.tableView setEditing:NO animated:YES];
    }
    
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self performSegueWithIdentifier:@"note2edit" sender:nil];
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    
    NSString *str = segue.identifier;
    
    if ([str isEqualToString:@"note2add"]) {
        NoteAddController *add = segue.destinationViewController;
        add.delegate = self;
    } else if ([str isEqualToString:@"note2edit"]) {
        NoteEditController *edit = segue.destinationViewController;
        
        NSIndexPath *path = [self.tableView indexPathForSelectedRow];
        
        edit.delegate = self;
        edit.note = self.noteArr[path.row];
    }
}


@end
